/*
 * Powered By XY
 * Since 2020
 */

package com.xy.biz.ts.service.impl;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import com.xy.biz.base.client.AttachmentClient;
import com.xy.biz.base.domain.req.ListAttachmentRequest;
import com.xy.biz.base.domain.resp.GetAttachmentResponse;
import com.xy.biz.ts.domain.bo.PracticeRecordConstants;
import com.xy.biz.ts.domain.bo.TrainBO;
import com.xy.biz.ts.domain.converter.PracticeRecordConverter;
import com.xy.biz.ts.domain.query.TrainQuery;
import com.xy.biz.ts.domain.resp.GetPracticeRecordResponse;
import com.xy.biz.ts.manager.TrainManager;
import com.xy.biz.uc.client.UserClient;
import com.xy.biz.uc.domain.constant.RoleConstant;
import com.xy.biz.uc.domain.dto.UserDTO;
import com.xy.biz.uc.domain.req.GetUserRequest;
import com.xy.lang.util.ResultUtils;
import com.xy.tool.context.UserContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xy.lang.domain.Result;
import com.xy.biz.ts.domain.bo.PracticeRecordBO;
import com.xy.biz.ts.domain.query.PracticeRecordQuery;
import com.xy.biz.ts.service.PracticeRecordService;
import com.xy.biz.ts.manager.PracticeRecordManager;
import org.springframework.util.CollectionUtils;

/**
 *
 *
 * @author wwj
 * @date 2021-4-7
 */
@Service
public class PracticeRecordServiceImpl implements PracticeRecordService {

    @Autowired
    private PracticeRecordManager practiceRecordManager;

    @Autowired
    private AttachmentClient attachmentClient;

    @Autowired
    private UserClient userClient;

    @Autowired
    private TrainManager trainManager;

    @Override
    public Result<?> savePracticeRecord(PracticeRecordBO practiceRecordBO) {
        build(practiceRecordBO);
        Result<List<GetAttachmentResponse>> listResult = attachmentClient.listAttachment(ListAttachmentRequest.builder().bizId(practiceRecordBO.getPracticeRecordId()).bizType(1).build());
        if (listResult.wasSuccess()) {
            List<GetAttachmentResponse> data = listResult.getData();
            if (data.size() == 0) {
                return Result.ofNotFound("未插入附件");
            }
        }
        int affectedRows = practiceRecordManager.savePracticeRecord(practiceRecordBO);
        if (affectedRows > 0) {
            return Result.success();
        }
        return Result.ofErrorRowsAffected();
    }

    private void build(PracticeRecordBO practiceRecordBO) {
        practiceRecordBO.setCreateTime(LocalDateTime.now());
        practiceRecordBO.setCreateUserId(UserContextHolder.getUserId());
        practiceRecordBO.setTrainId(practiceRecordBO.getTrainId());
        practiceRecordBO.setDeleteFlag(false);
        practiceRecordBO.setPassFlag(PracticeRecordConstants.PASS_FLAG_NOT_EVALUATE);
        practiceRecordBO.setPracticeUserId(UserContextHolder.getUserId());
        practiceRecordBO.setPracticeUserName(UserContextHolder.getUserName());
        practiceRecordBO.setTenantId(UserContextHolder.getTenantId());
        practiceRecordBO.setUpdateTime(LocalDateTime.now());
    }

    @Override
    public Result<?> saveAllPracticeRecord(Collection<PracticeRecordBO> collection) {
        int affectedRows = practiceRecordManager.saveAllPracticeRecord(collection);
        if (affectedRows > 0) {
            return Result.success();
        }
        return Result.ofErrorRowsAffected();
    }

    @Override
    public Result<?> updatePracticeRecord(PracticeRecordBO practiceRecordBO) {
        updateBO(practiceRecordBO);
        int affectedRows = practiceRecordManager.updatePracticeRecord(practiceRecordBO);
        if (affectedRows > 0) {
            return Result.success();
        }
        return Result.ofErrorRowsAffected();
    }

    private void updateBO(PracticeRecordBO practiceRecordBO) {
        practiceRecordBO.setUpdateTime(LocalDateTime.now());
        practiceRecordBO.setCommentUserId(UserContextHolder.getUserId());
    }

    @Override
    public Result<?> deletePracticeRecord(Long practiceRecordId) {
        int affectedRows = practiceRecordManager.deletePracticeRecord(practiceRecordId);
        if (affectedRows > 0) {
            return Result.success();
        }
        return Result.ofErrorRowsAffected();
    }

    @Override
    public Result<?> getPracticeRecord(Long practiceRecordId) {
        PracticeRecordBO practiceRecord = practiceRecordManager.getPracticeRecord(practiceRecordId);
        Result<List<GetAttachmentResponse>> listResult = attachmentClient.listAttachment(ListAttachmentRequest.builder().bizId(practiceRecordId).bizType(1).build());
        if (listResult.wasSuccess()) {
            List<GetAttachmentResponse> data = listResult.getData();
            practiceRecord.setAttachmentListResult(data);
            return Result.success(practiceRecord);
        }
        return Result.ofErrorRowsAffected();


    }

    @Override
    public List<PracticeRecordBO> listPracticeRecordById(Collection<Long> collection) {
        return practiceRecordManager.listPracticeRecordById(collection);
    }

    @Override
    public List<PracticeRecordBO> listPracticeRecord(PracticeRecordQuery query) {
        return practiceRecordManager.listPracticeRecord(query);
    }

    /**
     * 查找多个
     *
     * @param query 查找条件
     */
    @Override
    public List<GetPracticeRecordResponse> listPracticeRecord1(PracticeRecordQuery query) {
        List<PracticeRecordBO> practiceRecordBOS = practiceRecordManager.listPracticeRecord(query);
        if (CollectionUtils.isEmpty(practiceRecordBOS)) {
            return Collections.emptyList();
        }
        return PracticeRecordConverter.toResponse(practiceRecordBOS);
    }

    @Override
    public int countPracticeRecord(PracticeRecordQuery query) {
        Long userId = UserContextHolder.getUserId();
        UserDTO userDTO = ResultUtils.get(userClient.getUser(GetUserRequest.builder().withRole(true).userId(userId).build()));
        List<String> roleList = userDTO.getRoleList().stream().map(u -> u.getCode()).collect(Collectors.toList());
        if (!roleList.contains(RoleConstant.MANAGEMENT_TRAINER)) {
            query.setPracticeUserId(userId);
        }
        return practiceRecordManager.countPracticeRecord(query);
    }

}
